package com.example.sy4;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String[] foodName = request.getParameterValues("choice");

        if (foodName != null) {
            for (String item : foodName) {
                request.getSession().setAttribute(item, item);
            }
        }

        String url = "<a href='cart'>欢迎去购物车页面！</a>";
        response.getWriter().print("<p>点击超链接，链接到购物车页面, 查看购物车中的商品。<br />" + url);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    public static class LastAccessServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            String lastAccessTime = null;

            // 获取所有的cookie，并将这些cookie存放在数组中
            Cookie[] cookies = request.getCookies();

            // 遍历cookies数组
            for (int i = 0; cookies != null && i < cookies.length; i++) {
                if ("lastAccess".equals(cookies[i].getName())) {
                    // 如果cookie的名称为lastAccess,则获取该cookie的值
                    lastAccessTime = cookies[i].getValue();
                    break;
                }
            }

            // 判断是否存在名称为lastAccess的cookie
            if (lastAccessTime == null) {
                response.getWriter().print("您是首次访问本站！！！");
            } else {
                response.getWriter().print("您上次的访问时间是： " + lastAccessTime);
            }

            // 创建cookie,将当前时间作为cookie的值发送给客户端
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            Cookie cookie = new Cookie("lastAccess", currentTime);
            cookie.setMaxAge(60 * 60 * 24); // 设置cookie有效期为一天
            response.addCookie(cookie);
        }

        public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doGet(req, resp);
        }
    }
}




